//
//  XLTextView.swift
//  SinaWeibo
//
//  Created by 李凯 on 16/9/11.
//  Copyright © 2016年 kevin. All rights reserved.
//

import UIKit

class XLTextView: UITextView {
    
    var placeHolder: String? {
        didSet{
            placeHolderLabel.text = placeHolder
        }
    }
    
    override var font: UIFont? {
        didSet{
            placeHolderLabel.font = font
        }
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
        
        NotificationCenter.default.addObserver(self, selector: #selector(textDidChange), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        //添加占位文字的label
        addSubview(placeHolderLabel)
        //布局
        placeHolderLabel.snp_makeConstraints { (make) in
            make.left.equalTo(self).offset(5)
            make.top.equalTo(self).offset(8)
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        placeHolderLabel.snp_updateConstraints { (make) in
            //当文字过多时, 需要设置label的宽
            make.width.lessThanOrEqualTo(self.frame.width - 2 * 5)
        }
    }
    
    //系统一发送通知, 就执行该方法
    func textDidChange() {
        placeHolderLabel.isHidden = hasText
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    
    //懒加载
    lazy var placeHolderLabel: UILabel = {
        let label = UILabel(textColor: UIColor.darkGray, fontSize: 12)
        label.numberOfLines = 0
        return label
    }()
}


